package org.apache.felix.dm.impl.dependencies.bi;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;

public class ServiceProxy implements InvocationHandler {

	private final Object target;
	private final Map<String, Toggle> toggles;

	ServiceProxy(Object target, Map<String, Toggle> toggles) {
		this.target = target;
		this.toggles = toggles;
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		Object result = method.invoke(target, args);
		if (toggles.keySet().contains(method.getName())) {
			Toggle toggle = toggles.get(method.getName());
			// toggle switch
			if (args[0] != null) {
				toggle.setAvailable(true);
			} else {
				toggle.setAvailable(false);
			}
		}
		return result;
	}
	
	public Object getTarget() {
		return target;
	}

}
